package com.haixin.security.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 认证失败后，处理代码逻辑*/
@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    //登录失败后的访问地址
    private  String url;

    /*是否是重定向*/
    private Boolean isRedirect;

    public MyAuthenticationFailureHandler(String url, Boolean isRedirect){
        this.url = url;
        this.isRedirect = isRedirect;
    }



    /**
     * 认证失败后，处理的具体逻辑
     *
     * exception： 认证失败异常对象
     * */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("onAuthenticationFailure执行");
        if (isRedirect){
            /*重定向*/
            response.sendRedirect(url);
        }else {
//            请求转发
            request.getRequestDispatcher(url).forward(request,response);
        }
    }
}
